import time
from datetime import datetime, date
from common import *
from mysql import *

def getWeather(province = None, city = None, cip = None):
    # 如果有公网ip，则通过公网Ip查省市位置
    if cip != None:
        # address = WhereAddress()
        # list = address.getaddress(cip)
        # province = list[0]
        # city = list[1]
        # 使用geolite2获取省市
        geolite2 = seperate_ip(cip)
        province_names = trim_district_name(geolite2['Country_SpecificNameCN'])
        city_names = trim_district_name(geolite2['City_NameCN'])
        province = province_names['name']
        city = city_names['name']

    sqlconnect = MysqlConnect()
    # 拿到所在省市的id
    citysql = f'select id from district where name = "{city}" and id like concat((select id from district where name = "{province}" and length(id) = 3),"%")'
    cityid = sqlconnect.select(citysql)[0]['id']
    # 操作日期
    date = time.strftime('%y%m%d', time.localtime())

    # 拿天气信息
    # weathersql = f'select * from weather where city_id = "{cityid}" and date = "{date}"'
    weathersql = f'select a.*, b.ps_pm25, b.level, b.level_num ' \
                 f'from weather a left join ps_pm25 b on a.city_id = b.city_id and a.date = b.date ' \
                 f'where a.city_id = "{cityid}" and a.date = "{date}"'

    weather = sqlconnect.select(weathersql)
    # 如果当天该城市天气情况数据库中没有，则去更新
    if len(weather) == 0:
        updateWeather(province, city, cityid, date)
        weather = sqlconnect.select(weathersql)
    else:
        # 因为百度的天气情况每10分钟更新一次，所以，如果距上次更新超过了10分钟，则再次刷新
        timelast = datetime.strptime(weather[0]['update_time'], '%Y-%m-%d %H:%M')
        timenow = datetime.now()
        seconds = (timenow - timelast).seconds
        if seconds / 60 > 10:
            updateWeather(province, city, cityid, date)
            weather = sqlconnect.select(weathersql)

    sqlconnect.__close__()
    return weather[0]


# 参数增加cityid和date，避免重复查询
def updateWeather(province, city, cityid, date):
    urlencoder = UrlEncode()
    weathernews = MyWeatherNews(urlencoder.urlEncode(province), urlencoder.urlEncode(city))
    todaydata = weathernews.getWeatherNews()
    todayweather = todaydata['weather']
    psPm25 = todaydata['psPm25']

    sqlconnect = MysqlConnect()

    todayweather.update({'city_id': cityid, 'date': date})
    rowcount = sqlconnect.replace(todayweather, Weather())
    if rowcount != 'error':
        print('影响weather表' + str(rowcount) + '条数据')

    pspmlist = ['优', '良']
    psPm25.update({'city_id': cityid, 'date': date, 'level_num': pspmlist.index(psPm25['level'])})
    rowcount = sqlconnect.replace(psPm25, PsPm25())
    if rowcount != 'error':
        print('影响ps_pm25表' + str(rowcount) + '条数据')

    sqlconnect.__close__()
